package com.glkj.vipsystem.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.glkj.vipsystem.common.exception.BizException;
import com.glkj.vipsystem.common.utils.Constant;
import com.glkj.vipsystem.entity.ao.CompanyAO;
import com.glkj.vipsystem.entity.ao.GoodsAO;
import com.glkj.vipsystem.entity.ao.GoodsCatAO;
import com.glkj.vipsystem.entity.ao.VipCardAO;
import com.glkj.vipsystem.mapper.CompanyMapper;
import com.glkj.vipsystem.modules.sys.entity.SysUserEntity;
import com.glkj.vipsystem.modules.sys.entity.SysUserRoleEntity;
import com.glkj.vipsystem.modules.sys.service.SysUserRoleService;
import com.glkj.vipsystem.modules.sys.service.SysUserService;
import com.glkj.vipsystem.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * Company 服务实现类
 * </p>
 *
 * @author Limuchan
 * @since 2019-08-28 09:51:08
 */
@Service
public class CompanyService extends ServiceImpl<CompanyMapper, CompanyAO> implements ICompanyService {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private IShopService shopService;
    @Resource
    private IGoodsCatService goodsCatService;
    @Resource
    private IGoodsService goodsService;
    @Resource
    private IVipCardService vipCardService;

    /**
     * 新增公司
     *
     * @param company 公司信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(CompanyAO company, Long createUserId) {
        if (company == null) {
            throw new BizException("公司信息错误");
        }

        // 新增管理员
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setStatus(1);
        sysUser.setCreateUserId(createUserId);
        sysUser.setUsername(company.getUsername());
        sysUser.setPassword(company.getPassword());
        sysUser.setCreateTime(new Date());

        // 公司管理员角色
        List<Long> roleIds = new ArrayList<>();
        roleIds.add(Constant.Role.COMPANY.getValue());
        sysUser.setRoleIdList(roleIds);

        try {
            sysUserService.save(sysUser);
        } catch (DuplicateKeyException e) {
            throw new BizException("登录账号重复");
        }

        // 保存公司
        try {
            company.setStatus(1);
            company.setCreateTime(new Date());
            company.setMaxShopNum(null);
            company.setMaxEmployeeNum(null);
            super.insert(company);
        } catch (DuplicateKeyException e) {
            throw new BizException("公司名称或管理员手机号重复");
        }
    }

    /**
     * 修改公司信息
     *
     * @param company 公司信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CompanyAO company) {
        // 若修改密码 修改登录账号的密码
        String username = company.getUsername();
        SysUserEntity sysUserEntity = sysUserService.queryByUserName(username);
        if (sysUserEntity != null) {
            if (StringUtils.isNotBlank(company.getPassword())) {
                sysUserEntity.setPassword(new Sha256Hash(company.getPassword(), sysUserEntity.getSalt()).toHex());
            } else {
                sysUserEntity.setPassword(null);
            }
            sysUserEntity.setStatus(company.getStatus());
            sysUserService.updateById(sysUserEntity);
        }

        // 修改公司信息
        try {
            company.setMaxShopNum(null);
            company.setMaxEmployeeNum(null);
            super.updateById(company);
        } catch (DuplicateKeyException e) {
            throw new BizException("公司名称或管理员手机号重复");
        }
    }

    /**
     * 修改公司密码
     *
     * @param company 公司信息
     */
    @Override
    public void updatePassword(CompanyAO company) {
        // 修改密码
        String username = company.getUsername();
        SysUserEntity sysUserEntity = sysUserService.queryByUserName(username);
        if (sysUserEntity != null) {
            if (StringUtils.isNotBlank(company.getPassword())) {
                sysUserEntity.setPassword(new Sha256Hash(company.getPassword(), sysUserEntity.getSalt()).toHex());
            } else {
                sysUserEntity.setPassword(null);
            }
            sysUserService.updateById(sysUserEntity);
        }
    }

    /**
     * 批量删除
     *
     * @param companyIds 要删除的id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Integer> companyIds) {
        if (CollectionUtils.isEmpty(companyIds)) {
            return;
        }
        StringBuilder companyIdsSb = new StringBuilder();
        for (Integer companyId : companyIds) {
            companyIdsSb.append(",").append(companyId);
        }
        String companyIdsStr = companyIdsSb.toString().substring(1);
        // 删除公司管理员后台登录账号
        List<SysUserEntity> userEntityList = sysUserService.selectList(
                new EntityWrapper<SysUserEntity>()
                        .where("username in (select username from t_company where id in (" + companyIdsStr + "))")
        );
        if (!CollectionUtils.isEmpty(userEntityList)) {
            List<Long> userIds = new ArrayList<>();
            for (SysUserEntity sysUserEntity : userEntityList) {
                userIds.add(sysUserEntity.getUserId());
            }
            sysUserService.deleteBatchIds(userIds);
            sysUserRoleService.delete(
                    new EntityWrapper<SysUserRoleEntity>()
                            .in("user_id", userIds)
            );
        }
        // 删除店铺
        shopService.deleteByCompany(companyIds);
        // 删除公司商品分类 商品
        goodsCatService.delete(
                new EntityWrapper<GoodsCatAO>()
                        .in("company_id", companyIds)
        );
        goodsService.delete(new EntityWrapper<GoodsAO>().in("company_id",companyIds));

        // 删除公司下的会员卡
        vipCardService.delete(new EntityWrapper<VipCardAO>().in("company_id",companyIds));

        // 删除公司
        this.deleteBatchIds(companyIds);
    }
}
